from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.notice_center.models.nc_log_alarm_record import NCLogAlarmRecord
from common.utils import CommonTimeUtils

class NCLogAlarmRecordHandler():
    """  LogAlarmRecord Handler
    """
    def __init__(self):
        pass


    def get_log_alarm_record_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取日志告警记录信息
        """
        try:
            field_info = {field: value}
            order_info = {"alarm_state": "asc", "update_at": "desc"}
            result = NCLogAlarmRecord.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get log alarm record search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get log alarm record search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result



    def get_log_alarm_record_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取日志告警记录信息
        """
        try:
            result = NCLogAlarmRecord.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get log alarm record match, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get log alarm record match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def update_log_alarm_record(self, db: Session, data: dict):
        """
        修改日志告警记录信息
        """
        try:
            log_alarm_record_object = NCLogAlarmRecord.get_object_by_uuid(db, data["uuid"])
            if not log_alarm_record_object:
                # 如果不存在， 则异常返回
                logger.error(f"update log alarm record failed,{data['uuid']} not exist")
                return False
            
            if data["comment"] == "": return True
            
            result = NCLogAlarmRecord.update(db, data)
            if not result:
                logger.error(f"update log alarm record to database failed")
                return False
        except Exception as e:
            message = f"update log alarm record error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def delete_log_alarm_record(self, db: Session, data: dict):
        """
        删除日志告警记录信息
        """
        try:
            log_alarm_record_object = NCLogAlarmRecord.get_object_by_uuid(db, data['uuid'])
            if not log_alarm_record_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete log alarm record failed, uuid:{data['uuid']} not exist")
                return False

            # 删除告警记录
            NCLogAlarmRecord.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete log alarm record uuid:{data['uuid']}  error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def get_nc_log_alarm_status(self, db: Session):
        try:
            for watchdog in ["customLogWatchDog", "serviceLogWatchDog"]:
                watchdog_info = NCLogAlarmRecord.get_object_info_for_watchdog(db, watchdog)
                if not watchdog_info:
                    logger.error(f"alarm watchdog:{watchdog} not exist")
                    return False

                now_timestamp = datetime.now().timestamp()
                watchdog_timestamp = datetime.timestamp(CommonTimeUtils.strptime(watchdog_info["update_at"]) + timedelta(minutes=15))
                if watchdog_timestamp < now_timestamp:
                    logger.error(f"alarm watchdog:{watchdog} no alarm last 15 minutes => {watchdog_info}")
                    return False
        except Exception as e:
            message = f"get alarm status error"
            logger.exception(f"{message} => {e}")
            return False

        return True
